import json
import os

from scrapy import cmdline

from novel.config.rules import CHAPTER_RULES, RULES, UPDATA_RULES
from novel.utils.redis_utils import rcon, service
from novel.utils.tool import TOOL


def send(msg):
    pubsub_channel = 'result-book'
    ps = rcon.pubsub()
    ps.subscribe(pubsub_channel)
    rcon.publish(pubsub_channel, msg)

def read():
    pubsub_channel = 'add-book'
    ps = rcon.pubsub()
    ps.subscribe(pubsub_channel)
    TOOL.logging().info("启动服务成功，可以发送请求：")
    for i in  ps.listen():
        if i['type'] == 'message':
            s=i['data'].decode()
            coller(s)


def add_chapter(data):
    """
    添加章节方法
    :param data:
    :return:
    """
    try:
        url = data.get('url')
        id = data.get('id')
        no = data.get('no')
        if url == None and id == None and no == None:
            return
        cmd=CHAPTER_RULES.get(TOOL.get_host_url(url))%(id,url,no)
        os.system(cmd)
    except:
        TOOL.logging().info("添加章节出错")




def add_novel(data):
    """
    添加小说方法
    :param data:
    :return:
    """
    try:
        if data.get('url')==None:
            return
        cmd=RULES.get(TOOL.get_host_url(data.get('url'))) % data.get('url')

        os.system(cmd)

    except:
        TOOL.logging().info("添加小说出错")


def updata_novel(data):
    try:
        if data.get('id') == None and data.get('source'):
            return
        cmd=UPDATA_RULES.get(TOOL.get_host_url(data.get('source'))) % data.get('id')
        os.system(cmd)

    except:
        TOOL.logging().info('更新小说出错')


control_map={'chapter':add_chapter,'novel':add_novel,'updata':updata_novel}




@service
def coller(data):
    """
    新消息处理方法
    :param data:
    :return:
    """
    try:
        data_json=json.loads(data)
        method = control_map.get(data_json.get('type'))
        method(data_json)
    except:
        TOOL.logging().info('错误的json请求')
    TOOL.logging().info("执行完成。。。。")






if __name__ == '__main__':
    # p = multiprocessing.Process(target=read)
    # p.start()
    read()
    # p = factory_novel("http://www.ihuaben.com/book/592990.html")
    # p.insert()


